package com.fofia.iotweb.web.controllers.admin;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import com.fofia.iotweb.App;
import com.fofia.iotweb.Contants.SolonBootConfigDto;
import com.fofia.iotweb.cache.UserCache;
import com.fofia.iotweb.common.IdHelper;
import com.fofia.iotweb.common.MimeTypeUtils;
import com.fofia.iotweb.framework.core.BaseController;
import com.fofia.iotweb.framework.core.RequestHelper;
import com.fofia.iotweb.web.dbdomain.models.admin.SysUser;
import com.fofia.iotweb.web.dbdomain.services.admin.SysRoleService;
import com.fofia.iotweb.web.dbdomain.services.admin.SysUserService;
import com.fofia.iotweb.web.dto.*;
import org.apache.ibatis.annotations.Update;
import org.noear.solon.Solon;
import org.noear.solon.annotation.*;
import org.noear.solon.auth.annotation.AuthPermissions;
import org.noear.solon.core.handle.Context;
import org.noear.solon.core.handle.ModelAndView;
import org.noear.solon.core.handle.UploadedFile;

import java.io.File;
import java.io.IOException;
import java.lang.ref.PhantomReference;
import java.net.URL;
import java.nio.file.Paths;
import java.util.List;

@Mapping("/admin/user")
@Controller
public class UserController extends BaseController {

    @Inject
    private RequestHelper requestHelper;
    @Inject
     private SysUserService userService;
    @Inject
    private SysRoleService roleService;
    @Inject
    private UserCache userCache;
    @Inject
    private SolonBootConfigDto solonBootConfigDto;

    /**
     * 用户信息
     * @return
     */
    @Get
    @Mapping("index")
    @AuthPermissions("admin.user.view")
    public ModelAndView index(){

        return view();
    }

    @Post
    @Mapping("getPageList")
    @AuthPermissions("admin.user.view")
    public DataTableDto getPageList(DataTableDto dto){

        String loginName=requestHelper.getString("loginName","");
        String userName=requestHelper.getString("userName","");
        String phone=requestHelper.getString("phone","");
        var data=userService.getPageList(dto.getPageNumber(),dto.getPageSize(),loginName,userName,phone);
        return data;
    }

    @Get
    @Mapping("form")
    @AuthPermissions("admin.user.add;admin.user.edit")
    public ModelAndView form(){
          String id=requestHelper.getString("id","0");
        List<KeyValueInt64Dto> roles=roleService.getRoles();
        return view().put("id",id).put("roles",roles);
    }

    /**
     *
     * @author yushuo
     * @description //获取用信息
     * @date 13:59 2021/2/6
     **/
    @Get
    @Mapping("/getModel")
    @AuthPermissions("admin.user.add;admin.user.edit")
    public ResultAdaptDto getModel(String id){

        if(StrUtil.isEmpty(id)|| "0".equals(id)){
            return JsonResult.failure("用户信息不存在");
        }

        SysUser user=userService.getModel(Convert.toLong(id));
        if(user==null){

            return JsonResult.failure("用户信息不存在");
        }
        ResultAdaptDto result=new ResultAdaptDto();
        result.getData().put("model",user);
        return result;
    }

    /**
     *
     * @author yushuo
     * @description //保存数据
     * @date 13:58 2021/2/6
     **/
    @Post
    @Mapping("/save")
    @AuthPermissions("admin.user.add;admin.user.edit")
    public ResultAdaptDto save(SysUser dto){
        if(StrUtil.isEmpty(dto.getUserName())||StrUtil.isEmpty(dto.getPassWord())){
            return JsonResult.failure("用户名密码验证失败");
        }
        String[] position=requestHelper.getStringArray("position");

        boolean userExists= userService.userExists(dto);
        if(userExists){
            return JsonResult.failure(StrUtil.format("登录账号[{}]已存在",dto.getLoginName()));
        }
        userService.save(dto,position,userCache.getUserSeesion());
        return JsonResult.success("用户保存成功");
    }


    /**
     *
     * @author yushuo
     * @description 删除用户
     * @date 13:58 2021/2/6
     **/
    @Post
    @Mapping("/removeAll")
    @AuthPermissions("admin.user.delete")
    public ResultAdaptDto removeAll(){
        String ids=requestHelper.getString("ids","");
        if(StrUtil.isEmpty(ids)){
            return JsonResult.failure("参数错误");
        }

        userService.removeAll(ids);
        return JsonResult.success("用户已删除");
    }

    @Get
    @Mapping("/resetPassword")
    @AuthPermissions("admin.user.password")
    public ModelAndView resetPassword(){
        String id=requestHelper.getString("id","0");
        String loginName=requestHelper.getString("loginName","");
         return view().put("id",id)
                 .put("loginName",loginName);
    }

    /***
     * 更新密码
     * @return
     */
    @Post
    @Mapping("/updatePassword")
    @AuthPermissions("admin.user.password;admin.user.profile")
    public ResultAdaptDto updatePassword(){
        long id = requestHelper.getInt64("id", 0L);
        String newPassword = requestHelper.getString("newPassword", "");
        String accountName = requestHelper.getString("loginName", "");
        if(id<1){
            return JsonResult.failure("参数错误");
        }

        ResultAdaptDto ret=userService.updatePassword(id,newPassword.trim());
        return  ret;
    }

    @Get
    @Mapping("/selfResetPassword")
    @AuthPermissions("admin.user.profile")
    public ModelAndView selfResetPassword(){

        LoginUserDto user=userCache.getUserSeesion();
        return view().put("id",user.getUserId())
                .put("loginName",user.getLoginName());
    }

    @Get
    @Mapping("/profile")
    @AuthPermissions("admin.user.profile")
    public ModelAndView profile(){
        LoginUserDto user=userCache.getUserSeesion();

        //user.setEmail("461733078@qq.com");
        return view().put("user",user);
    }


    @Post
    @Mapping("/updateProfile")
    @AuthPermissions("admin.user.profile")
    public ResultAdaptDto updateProfile(LoginUserDto user){
       // LoginUserDto user=userCache.getUserSeesion();

        //user.setEmail("461733078@qq.com");
        ResultAdaptDto ret =userService.updatePorfile(user);
        if(ret.isStatus()){
            LoginUserDto userCacheModel=userCache.getUserSeesion();
            userCacheModel.setUserName(user.getUserName());
            userCacheModel.setTel(user.getTel());
            userCacheModel.setEmail(user.getEmail());
            userCacheModel.setGender(user.getGender());
            userCache.setCache(userCacheModel);
        }
        return ret;
    }

    @Get
    @Mapping("/avatar")
    @AuthPermissions("admin.user.profile")
    public ModelAndView avatar(){
        LoginUserDto user=userCache.getUserSeesion();
        String avatar="/ui/images/profile.jpg";
        if(!StrUtil.isEmpty(user.getAvatar())){
            avatar=user.getAvatar();
        }
        return view().put("avatar",avatar);
    }

    @Post
    @Mapping(path="/updateAvatar", multipart=true)
    @AuthPermissions("admin.user.profile")
    public ResultAdaptDto updateAvatar( Context ctx){

        try{
            UploadedFile file = ctx.file("avatarfile"); //UploadedFile[] file= ctx.files("file"); 同名多文件
             if(file==null){
                 return JsonResult.failure("上传失败");
             }
            String newFileName = IdHelper.objectId() +"."+ MimeTypeUtils.getExtension(file.getContentType());
           // StaticLog.info(newFileName);
            String dir=solonBootConfigDto.getResourceDir();
            String relativePath="/uploads/avatar/"+newFileName;
            java.nio.file.Path basePath = Paths.get(dir, relativePath);
            String localPath=  basePath.toAbsolutePath().toString();

            file.transferTo(new File(localPath));

            LoginUserDto user=userCache.getUserSeesion();
            userService.updateAvatar(user.getUserId(),relativePath);
             user.setAvatar(relativePath);
              userCache.setCache(user);
           // StaticLog.info(localPath);
            return JsonResult.success("头像已更新");
        }catch (IOException ex){
            StaticLog.error(ex);
        }finally {
            //用完之后，删除"可能的"临时文件 //v2.7.2 后支持
            //file.delete();
        }

        return JsonResult.failure("更新失败");
    }
}
